home *** CD-ROM | disk | FTP | other *** search
- Path: rcp6.elan.af.mil!rscernix!danpop
- From: danpop@mail.cern.ch (Dan Pop)
- Newsgroups: comp.lang.c
- Subject: Re: HELP: Illegal Pointer Arithmetic
- Date: 24 Feb 96 00:18:59 GMT
- Organization: CERN European Lab for Particle Physics
- Message-ID: <danpop.825121139@rscernix>
- References: <4gj0ug$730@news.one.net>
- NNTP-Posting-Host: ues5.cern.ch
- X-Newsreader: NN version 6.5.0 #7 (NOV)
-
- In <4gj0ug$730@news.one.net> Oren Levin <oren@one.net> writes:
-
- > while (! feof (fin))
- ^^^^^^^^^^^^^^^^^^^^
- Are there any books teaching this idiocy or is it only Pascal-induced
- brain damage? (See the FAQ.)
-
- > {
- > /* read a record */
- > if (fgets (buffer, 127, fin) == NULL)
- > break;
- >
- > /* get rid of the trailing carrage return */
- > buffer [strlen (buffer) - 1] = "\0";
- ^^^^
- This is not an integral type that can be assigned to a char. Use either
- 0 or '\0' (apart from the visual aspect, they're one and the same thing).
- (OTOH, "\0" is a string literal containing two null characters. In a
- value context, it decays into a pointer to char and cannot be assigned
- to a character.)
-
- However, the code is unsafe, unless it is guaranteed that no line from
- the fin stream can possibly be longer than 126 characters (including the
- newline). If the line is longer, this code simply destroys the last
- character read from the stream. A safer approach would be:
-
- if ((p = strchr(buffer, '\n')) != NULL) *p = '\0';
-
- For some reason I like this better than:
-
- last = strlen(buffer) - 1;
- if (buffer[last] == '\n') buffer[last] = '\0';
-
- Dan
- --
- Dan Pop
- CERN, CN Division
- Email: danpop@mail.cern.ch
- Mail: CERN - PPE, Bat. 31 R-004, CH-1211 Geneve 23, Switzerland
-